package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @Classname CommonController
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/6/21 22:15
 * @Created by Ren
 */
@RestController
@RequestMapping("/admin/common")
@Api("通用接口")
@Slf4j
public class CommonController {

    @Resource
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {

        log.info("进入 /upload, file = {}", file);

        try {

            String originalFilename = file.getOriginalFilename();  //原始文件名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));  //获取文件名后缀 xxx.jpg
            String newFileName = UUID.randomUUID().toString() + extension; //利用UUID + 后缀名保证名称的唯一

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), newFileName);//参数一：文件的字节数组,参数二：上传到阿里云的图片名称

            return Result.success(filePath);

        } catch (IOException e) {
            log.info("文件上传失败 {}", e.getMessage());
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }


}
